package com.yc.damai.biz;

import java.util.ArrayList;
import java.util.List;

import com.yc.damai.bean.PageBean;
import com.yc.damai.bean.Product;
import com.yc.damai.dao.ProductDao;
import com.yc.damai.util.DBHelper;
import com.yc.damai.util.Utils;

public class ProductBiz {
	
	private ProductDao pdao = new ProductDao();
	
	public void save(Product p) throws BizException {
		/**
		 *  业务判断:
		 *  	1. 字段验证
		 *  	2. 同名判断 
		 */
		Utils.check(Utils.isEmpty(p.getPname()), "商品名不能为空");
		Utils.check(p.getPname().length()< 2, "商品名不能少于2个字符");
		Utils.check(p.getshopPrice()== null || p.getshopPrice()<=0, "商品售价不能小等于于0");
		// 修改不做同名验证
		Utils.check(p.getPid()==null && pdao.has(p.getPname()), "系统中已有该商品了");
		
		// pid 为空是新增, 否则是修改
		if(p.getPid()==null) {
			pdao.insert(p);
		} else {
			pdao.update(p);
		}
		
	}

	public PageBean page(PageBean pb) {
		String sql = "select * from product limit ?,?";
		int page = (pb.getPage() -1) * pb.getSize();
		List<Product> list =  DBHelper.query(sql, Product.class, page, pb.getSize());
		
		sql = "select count(*) cnt from product";
		int total = Integer.parseInt("" + DBHelper.query(sql).get(0).get("cnt"));
		
		pb.setTotal(total);
		pb.setList(list);
		
		return pb;
		
	}

	/**
	 * 组合条件查询
	 */
	public Object page(Product p, PageBean pb) {
		String sql = "select * from product where 1=1";
		ArrayList<Object> params = new ArrayList<>(); 
		
		if(Utils.isEmpty(p.getPname()) == false) {
			sql += " and pname like ?";
			params.add("%" + p.getPname() + "%");
		}
		
		if(p.getshopPrice() != null) {
			sql += " and shopPrice = ?";
			params.add(p.getshopPrice());
		}
		// 查询总数
		String sql2 = "select count(*) cnt from ( " + sql + " ) a";
		int total = Integer.parseInt(
				"" + DBHelper.query(sql2, params.toArray()).get(0).get("cnt"));

		// 查询数据
		String sql1 = sql + " limit ?, ?"; 
		int page = (pb.getPage() -1) * pb.getSize();
		params.add(page);
		params.add(pb.getSize());
		List<Product> list =  DBHelper.query(sql1, Product.class, params.toArray());
		
		
		pb.setTotal(total);
		pb.setList(list);
		
		return pb;
	}

}
